package feifei.dao.impl;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import feifei.dao.UserDao;
import feifei.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

public class UserDaoImpl implements UserDao {
    @Override
    public ArrayList<User> findUserBySql(String sql) throws Exception {
        ArrayList<User> userList=new ArrayList<>();
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        DruidDataSource bean = (DruidDataSource) app.getBean("dataSource");
        DruidPooledConnection conn = bean.getConnection();
        PreparedStatement pstmt=conn.prepareStatement(sql);
        ResultSet rs=pstmt.executeQuery();
        while(rs.next()) {
            User u=new User();
            u.setId(rs.getInt("id"));
            u.setUsername(rs.getString("username"));
            u.setPassword(rs.getString("password"));
            userList.add(u);
        }
        conn.close();
        pstmt.close();
        return userList;
    }
}
